
// Copyright (c) WanSheng Intelligent Corp. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.


#include "endpoint.h"

WA_EDGE_CONTEXT wagent_ctx = NULL;
const char * g_my_device_id = "ep_001";

// the callback for the resource directory (RD) registration status
static void rd_status_handler (WA_EDGE_CONTEXT, bool success)
{
    printf("RD registration status: %s\n", success?"online":"offline");
}

int main(int argc, char * argv[])
{
    log_setlevel(LOG_VERBOSE);
    log_set_tag_mask(LOG_WAGENT_SDK_MASK_ID, 0xFFFF);
    log_set_tag_mask(LOG_MY_MASK_ID, 0xFFFFFFFF);

    // initiate the coap based restful framework
    RESTFUL_CONTEXT restful_context = wa_coap_init_context(-1, 1000, 0);

    // initiate the communication with wagent
    wagent_ctx = wa_wagent_init(restful_context, "127.0.0.1");

    // register two resources with the URI and handlers
    wa_coap_register_resource(restful_context, RES_FRE, res_frequence, T_Default);
    wa_coap_register_resource(restful_context, RES_CNT, res_count, T_Default);

    // set resource type for the resources, so it can be used for registering on the wagent
    wa_resource_set_type(restful_context, RES_FRE, "oic.abc");
    wa_resource_set_type(restful_context, RES_CNT, "oic.kkk");
    
    // prepare the resource directory report message
    rd_assemble_t rd = rd_data_init_A(g_my_device_id, "ep", "wasome.ble", true);
    // add all resource with type set using wa_resource_set_type()
    wa_load_resources_to_rd(restful_context, rd);
    // Tell the RD should updated every 10 seconds
    rd_data_set_ttl(rd, 10);
    // generate the message payload in JSON format
    char * RD_message = rd_data_payload_A(rd);
    rd_data_destroy(rd);

    // register the RD on wagent
    wa_wagent_set_rd(wagent_ctx, g_my_device_id, RD_message, 10*1000, rd_status_handler);

    // start the main loop for the restful framework handling all the messages
    while(1) 
    {
        // check the expiry of transactions
        uint32_t near_task_time = wa_coap_check_expiry(restful_context);

        // check for RD registeration updating for keeping online. 
        // It will send 2 RD updates every 10 seconds.
        uint32_t next = wa_agent_check_rd_registeration(wagent_ctx);

        if(near_task_time == -1) 
            near_task_time = next;
        else if(next != -1 && near_task_time > next)
            near_task_time = next;
        if(near_task_time == -1) near_task_time = 1000; 

        // doing blocking wait and ensured wakeup by the nearest expiration
        wa_coap_recieve_process(restful_context, (int)near_task_time);
    };

    return 0;
}
